<template>
  <el-button type="primary" v-per2="['order-list','post']" @click="doAdd">申请资源</el-button>
  <el-row style="margin-top:20px;">
    <el-form ref="searchFormRef" :inline="true" :model="state.searchForm">
      <el-form-item label="工单编号" prop="order_id">
        <el-input style="width: 150px;" v-model="state.searchForm.order_id" placeholder="工单编号" clearable/>
      </el-form-item>
      <el-form-item label="应用名称" prop="app_name">
        <el-input style="width: 150px;" v-model="state.searchForm.app_name" placeholder="应用名称" clearable/>
      </el-form-item>
      <el-form-item label="联系人" prop="contact_person">
        <el-input style="width: 150px;" v-model="state.searchForm.contact_person" placeholder="联系人" clearable/>
      </el-form-item>
      <el-form-item label="申请时间" prop="date_range">
        <el-date-picker
            v-model="state.searchForm.date_range"
            type="daterange"
            start-placeholder="起始"
            end-placeholder="结束"
            :shortcuts="shortcuts"
            style="width: 200px;"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSearch">搜 索</el-button>
        <el-button type="primary" @click="doResetSearchForm" plain>重 置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['order-list','get']" show-overflow-tooltip>
      <el-table-column type="selection" width="55" label="选择"/>
      <el-table-column sortable prop="order_id" label="工单编号" min-width="120">
        <template #default="scope">
          <el-link type="primary" @click="doView(scope.row,scope.$index)">{{ scope.row.order_id }}</el-link>
        </template>
      </el-table-column>
      <el-table-column sortable prop="apply_person" label="申请人"/>
      <el-table-column sortable prop="contact_person" label="联系人"/>
      <el-table-column sortable prop="contact_phone" label="联系电话"/>
      <el-table-column sortable prop="apply_depart" label="申请部门"/>
      <el-table-column sortable prop="app_name" label="应用名称"/>
      <el-table-column sortable prop="remarks" label="用途及业务说明"/>
      <el-table-column sortable prop="order_status_text" label="状态">
        <template #default="scope">
          <el-tag effect="light" :type="scope.row.order_status_style" size="large">
            {{ scope.row.order_status_text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column sortable prop="apply_datetime" label="申请时间"/>
      <el-table-column
          fixed="right"
          min-width="100"
          class="ml-4"
          v-if="hasButton([{name:'order-detail',method:'put'},{name:'order-detail',method:'patch'}])"
          label="资源分配"
      >
        <template #default="scope">
          <el-button-group>
            <el-button v-per2="['order-detail','put']" size="small"
                       class="card-small-btn" type="primary"
                       @click="doVmEdit(scope.row,scope.$index)"
            >计算
            </el-button>
            <el-button v-per2="['order-detail','put']" size="small"
                       class="card-small-btn" type="primary"
                       @click="doNetEdit(scope.row,scope.$index)">网络
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          min-width="120px"
          class="ml-4"
          v-if="hasButton([{name:'order-detail',method:'put'},{name:'order-detail',method:'patch'}])"
          label="操作"
      >
        <template #default="scope">
          <el-button-group>
            <el-button v-per2="['order-detail','put']" type="primary" size="small"
                       class="card-small-btn"
                       @click="doEdit(scope.row,scope.$index)"
            >编 辑
            </el-button>
            <el-popconfirm
                cancel-button-type="danger"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="confirmDelete(scope.row,scope.$index)"
                title="确认删除吗?">
              <template #reference>
                <el-button v-per2="['order-detail','delete']" type="danger" size="small"
                           class="card-small-btn">删除
                </el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <MinePager v-per2="['order-list','get']" :pager="state.pager"/>
  </el-row>
  <el-dialog v-model="state.dialog.visible"
             :show-close="false"
             style="padding: 0"
             draggable
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             :fullscreen="true"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="header">
        <span>{{ state.dialog.title }}</span>
        <el-link @click="close" :underline="false">
          <el-icon style="color: white">
            <Close/>
          </el-icon>
        </el-link>
      </div>
    </template>
    <div class="card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="never" body-style="padding-bottom:0;padding-left:0">
            <el-form :model="state.applyForm.form" ref="applyFormRef" :rules="state.applyForm.rules" label-width="120px"
                     label-position="right">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="联系人" prop="contact_person">
                    <el-input v-model="state.applyForm.form.contact_person" placeholder="联系人"></el-input>
                  </el-form-item>
                  <el-form-item label="信息系统名称" prop="app_name">
                    <el-input v-model="state.applyForm.form.app_name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="contact_phone" label="联系电话">
                    <el-input v-model="state.applyForm.form.contact_phone" placeholder="联系电话"></el-input>
                  </el-form-item>
                  <el-form-item label="申请时间">
                    <el-date-picker
                        v-model="state.applyForm.form.apply_datetime"
                        type="date"
                        placeholder="选择一个日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="用途" prop="remarks">
                    <el-input v-model="state.applyForm.form.remarks" type="textarea" maxlength="200" show-word-limit
                              :rows="3"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="center">
                <el-form-item>
                  <el-button @click="doSubmit" type="success" style="width: 150px;height: 40px">提交</el-button>
                  <el-button @click="doSave" type="primary" style="width: 150px;height: 40px">保存</el-button>
                  <el-button @click="state.dialog.visible=false" type="info" style="width: 150px;height: 40px">取 消
                  </el-button>
                </el-form-item>
              </el-row>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <el-upload
                :file-list="state.fileForm.fileList"
                :headers="state.fileForm.headers"
                accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
                :on-success="uploadSuccess"
                class="upload-demo"
                action="http://127.0.0.1:8000/api/web/order/upload/"
                multiple
                :before-upload="beforeUpload"
                :on-exceed="handleExceed"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :limit="6"
            >
              <el-button type="primary">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传jpg/jpeg/png/pdf/doc/docx/xls/xlsx/ppt/pptx文件，单个文件不超过50MB.
                </div>
              </template>
            </el-upload>
          </el-card>
        </el-col>
      </el-row>

    </div>
    <div class="card">
      <el-card shadow="never">
        <el-tabs type="border-card" class="resource-tabs">
          <el-tab-pane>
            <template #label>
            <span class="custom-tabs-label">
              <el-icon><Cpu/></el-icon>
              <span>计算（存储）资源</span>
            </span>
            </template>
            <el-form :inline="true" :model="state.vmForm.form" ref="vmFormRef" :rules="state.vmForm.rules">
              <el-form-item label="体系架构" prop="cpu_arch">
                <el-radio-group v-model="state.vmForm.form.cpu_arch">
                  <el-radio-button v-for="item in state.vmForm.options.cpu_arch" :label="item.label"
                                   :value="item.value"/>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="虚拟机名称" prop="vm_name">
                <el-input v-model="state.vmForm.form.vm_name" style="width: 200px;" placeholder="虚拟机名称(用途)" clearable/>
              </el-form-item>
              <el-form-item label="虚拟机规格" prop="flavor">
                <el-input
                    v-model="state.vmForm.form.flavor_text"
                    style="width: 250px"
                    placeholder="规格"
                    readonly
                >
                  <template #append>
                    <el-button @click="doSelectFlavor">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="操作系统" prop="os">
                <el-input
                    v-model="state.vmForm.form.os_text"
                    style="width: 450px"
                    placeholder="操作系统"
                    readonly
                    clearable
                >
                  <template #append>
                    <el-button @click="doSelectOs">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="数据盘大小(GiB)" prop="disk_size">
                <el-input-number
                    v-model="state.vmForm.form.disk_size"
                    :step="10"
                    :min="1"
                    style="width: 120px;margin-right: 10px;"
                    controls-position="right"
                />
              </el-form-item>
              <el-form-item label="网络位置" prop="net_location">
                <el-select
                    v-model="state.vmForm.form.net_location"
                    placeholder="选择"
                    style="width: 150px"
                >
                  <el-option
                      v-for="item in state.vmForm.options.net_location"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="安全分区" prop="security_domain">
                <el-select
                    v-model="state.vmForm.form.security_domain"
                    placeholder="选择"
                    style="width: 150px"
                >
                  <el-option
                      v-for="item in state.vmForm.options.security_domain"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="doAddVm(vmFormRef)">添加</el-button>
                <el-button @click="resetVmForm" type="primary">重 置</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="state.vmTableData" border style="width: 100%">
              <el-table-column sortable prop="vm_name" label="虚拟机名称"/>
              <el-table-column sortable prop="cpu_arch_text" label="CPU架构"/>
              <el-table-column sortable prop="flavor_text" label="规格"/>
              <el-table-column sortable prop="disk_size" label="数据盘大小(GB)"/>
              <el-table-column sortable prop="net_location_text" label="网络位置"/>
              <el-table-column sortable prop="security_domain_text" label="安全分区"/>

              <el-table-column
                  v-if="hasButton([{name:'flavor-detail',method:'put'},{name:'flavor-detail',method:'delete'}])"
                  label="操作">
                <template #default="scope">
                  <el-popconfirm
                      cancel-button-type="danger"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      @confirm="vmConfirmDelete(scope.$index,scope.row)"
                      title="确认删除吗?">
                    <template #reference>
                      <el-button type="danger" size="small" icon="Delete"
                                 class="card-small-btn">删 除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane>
            <template #label>
        <span class="custom-tabs-label">
          <el-icon><Connection/></el-icon>
          <span>网络资源</span>
        </span>
            </template>
            <el-form :inline="true" :model="state.netForm.form" ref="netFormRef" :rules="state.netForm.rules">
              <el-form-item label="资源名称" prop="resource_name">
                <el-input v-model="state.netForm.form.resource_name" style="width: 200px;" placeholder="资源名称"
                          clearable/>
              </el-form-item>
              <el-form-item label="网络位置" prop="net_location">
                <el-select
                    v-model="state.netForm.form.net_location"
                    placeholder="选择"
                    style="width: 150px"
                >
                  <el-option
                      v-for="item in state.netForm.options.net_location"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="安全分区" prop="security_domain">
                <el-select
                    v-model="state.netForm.form.security_domain"
                    placeholder="选择"
                    style="width: 150px"
                >
                  <el-option
                      v-for="item in state.netForm.options.security_domain"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="doAddNet(netFormRef)">添加</el-button>
                <el-button @click="resetNetForm" type="primary">重 置</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="state.netTableData" border style="width: 100%">
              <el-table-column type="selection" width="55" label="选择"/>
              <el-table-column label="序号">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column sortable prop="resource_name" label="资源名称"/>
              <el-table-column sortable prop="net_location_text" label="网络位置"/>
              <el-table-column sortable prop="security_domain_text" label="安全分区"/>
              <el-table-column
                  v-if="hasButton([{name:'flavor-detail',method:'put'},{name:'flavor-detail',method:'delete'}])"
                  label="操作">
                <template #default="scope">
                  <el-popconfirm
                      cancel-button-type="danger"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      @confirm="netConfirmDelete(scope.$index,scope.row)"
                      title="确认删除吗?">
                    <template #reference>
                      <el-button :disabled="scope.row.flag" type="danger"
                                 size="small" icon="Delete"
                                 class="card-small-btn">删 除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </el-dialog>
  <VmConfirmDialog :obj="state.vmConfirmDialog" :order_detail="state.order_detail" ref="allocationVmRuleForm"/>
  <NetConfirmDialog :obj="state.netConfirmDialog" :order_detail="state.order_detail" ref="allocationNetRuleForm"/>
  <OrderViewDrawer :obj="state.orderViewDrawer" :order_detail="state.order_detail" ></OrderViewDrawer>
  <SelectDrawer :obj="state.osDrawer" :click_event="doOsClickRow"/>
  <SelectDrawer :obj="state.flavorDrawer"/>
  <SelectDrawer :obj="state.allocationflavorDrawer"/>
  <SelectDrawer :obj="state.clusterDrawer"/>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MinePager from "@/components/MinePager.vue";
import SelectDrawer from "@/components/SelectDrawer.vue";
import VmConfirmDialog from "@/components/VmConfirmDialog.vue";
import NetConfirmDialog from "@/components/NetConfirmDialog.vue";
import OrderViewDrawer from "@/components/OrderViewDrawer.vue";
import {hasButton, hasPermission2} from "@/stores/permission.js";
import {userInfoStore} from "@/stores/counter.js";


const searchFormRef = ref(null)
const vmFormRef = ref()
const netFormRef = ref()
const applyFormRef = ref()
const allocationVmRuleForm = ref()
const allocationNetRuleForm = ref()
const info = userInfoStore()

const validateIP = (rule, value, callback) => {
  const ipReg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
  if (!ipReg.test(value)) {
    callback(new Error('请输入有效的IP地址'))
  } else {
    callback()
  }
}

const subnetMaskValidator = (rule, value, callback) => {
  // 标准子网掩码正则
  const maskRegex = /^(254|252|248|240|224|192|128|0)\.0\.0\.0$|^255\.(254|252|248|240|224|192|128|0)\.0\.0$|^255\.255\.(254|252|248|240|224|192|128|0)\.0$|^255\.255\.255\.(254|252|248|240|224|192|128|0)$|^255\.255\.255\.255$/;

  if (value && !maskRegex.test(value)) {
    callback(new Error('请输入有效的子网掩码（如255.255.255.0）'));
  } else {
    callback();
  }
}

const state = reactive({
  isLoading: false,
  vmTableData: [],

  flavorDrawer: {
    id: "",
    visible: false,
    title: '选择服务器规格',
    tableData: [],
    header: [
      {field_name: 'id', field_label: '规格ID'},
      {field_name: 'title', field_label: '规格名称'},
      {field_name: 'vcpu', field_label: 'CPU数量'},
      {field_name: 'memory', field_label: '内存大小(GB)'},
      {field_name: 'desc', field_label: '规格描述'},
    ],
    doSelectRow: doFlavorClickRow
  },
  clusterDrawer: {
    id: "",
    visible: false,
    title: '选择资源池',
    tableData: [
      {id: 1, cluster_name: 'SMARTX资源池', location: '3F18', cpu: '1530', memory: '1530', desc: '二楼资源池'},
      {id: 2, cluster_name: '浪潮资源池', location: '2F18', cpu: '1530', memory: '1530', desc: '二楼资源池'},
      {id: 3, cluster_name: 'H3C资源池', location: '2F28', cpu: '1530', memory: '1530', desc: '二楼资源池'},
      {id: 4, cluster_name: 'SMARTX资源池', location: '3F15', cpu: '1530', memory: '1530', desc: '二楼资源池'},
    ],
    header: [
      {field_name: 'id', field_label: '资源池ID'},
      {field_name: 'cluster_name', field_label: '资源池名称'},
      {field_name: 'location', field_label: '位置'},
      {field_name: 'cpu', field_label: 'cpu核数'},
      {field_name: 'memory', field_label: '内存大小(GB)'},
      {field_name: 'desc', field_label: '规格描述'},
    ],
    doSelectRow: doClusterClickRow
  },
  allocationflavorDrawer: {
    id: "",
    visible: false,
    title: '选择服务器规格',
    tableData: [],
    header: [
      {field_name: 'id', field_label: '规格ID'},
      {field_name: 'title', field_label: '规格名称'},
      {field_name: 'vcpu', field_label: 'CPU数量'},
      {field_name: 'memory', field_label: '内存大小(GB)'},
      {field_name: 'desc', field_label: '规格描述'},
    ],
    doSelectRow: doAllocationFlavorClickRow
  },
  osDrawer: {
    id: '',
    visible: false,
    title: '选择操作系统',
    tableData: [],
    header: [
      {field_name: 'id', field_label: '操作系统ID'},
      {field_name: 'os_type_text', field_label: '操作系统类型'},
      {field_name: 'os_name', field_label: '操作系统名称'},
      {field_name: 'os_abbr', field_label: '操作系统别名'},
      {field_name: 'version', field_label: '操作系统版本'},
    ],
    doSelectRow: doOsClickRow
  },
  netTableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: Number(localStorage.getItem("pageSize")) || 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  dialog: {
    visible: false,
    title: "",
  },
  fileForm: {
    headers: {
      Authorization: info.userToken
    },
    fileList: []
  },
  applyForm: {
    form: {
      contact_person: "",
      contact_phone: "",
      app_name: "",
      remarks: "",
      apply_datetime: new Date(),
    },
    rules: {
      contact_person: [
        {required: true, message: '请输入联系人', trigger: ['blur', 'change']},
      ],
      contact_phone: [
        {required: true, message: '请输入联系电话', trigger: ['blur', 'change']},
      ],
      app_name: [
        {required: true, message: '请输入应用名称', trigger: ['blur', 'change']},
      ],
      remarks: [
        {required: true, message: '请输入描述', trigger: ['blur', 'change']},
      ],
      apply_datetime: [
        {required: true, message: '请选择时间', trigger: ['blur', 'change']},
      ]
    },
  },
  vmForm: {
    form: {
      vm_name: '',
      cpu_arch: 1,
      cpu_arch_text: '',
      flavor: '',
      flavor_text: '',
      vcpu: '',
      memory: '',
      net_location: "",
      security_domain: "",
      disk_size: 100,
      os: "",
      os_text: '',
    },
    options: {
      cpu_arch: [
        {label: 'X86', value: 1},
        {label: 'ARM', value: 2}
      ],
      net_location: [
        {label: '内部服务网', value: 1},
        {label: '外部服务网', value: 2}
      ],
      security_domain: [
        {label: '基础设施区', value: 1},
        {label: '数据服务区', value: 2},
        {label: '应用服务区', value: 3},
        {label: '托管服务区', value: 4},
      ]
    },
    rules: {
      vm_name: [
        {required: true, message: '请输虚机名称', trigger: 'blur'},
      ],
      os: [
        {required: true, message: '请选择操作系统', trigger: 'change'},
      ],
      disk_size: [
        {required: true, message: '请输入数据盘大小', trigger: 'blur'},
      ],
      flavor: [
        {required: true, message: '请选择虚拟机规格', trigger: 'change'},
      ],
      cpu_arch: [
        {required: true, message: '请选择CPU架构', trigger: 'blur'},
      ],
      net_location: [
        {required: true, message: '请选择网络位置', trigger: 'change'},
      ],
      security_domain: [
        {required: true, message: '请选择安全分区', trigger: 'change'},
      ]
    },
  },
  netForm: {
    form: {
      net_location: '',
      net_location_text: '',
      security_domain: '',
      security_domain_text: '',
      resource_name: ''
    },
    options: {
      net_location: [
        {label: '内部服务网', value: 1},
        {label: '外部服务网', value: 2}
      ],
      security_domain: [
        {label: '基础设施区', value: 1},
        {label: '数据服务区', value: 2},
        {label: '应用服务区', value: 3},
        {label: '托管服务区', value: 4},
      ]
    },
    rules: {
      resource_name: [
        {required: true, message: '资源名称不能为空', trigger: 'blur'},
      ],
      net_location: [
        {required: true, message: '请选择网络位置', trigger: 'blur'},
      ],
      security_domain: [
        {required: true, message: '请选择安全分区', trigger: 'blur'},
      ]
    }
  },
  searchForm: {
    order_id: "",
    app_name: "",
    contact_person: "",
    date_range: "",
  },
  vmConfirmDialog: {
    editId: -1,
    editIndex: -1,
    flavorSelectId: -1,
    editVmId: -1,
    editVmIndex: -1,
    form: {
      table_data: [],
      process_method: 1,
      remarks: '请按照相关要求使用计算（存储）资源',
    },
    rules: {
      process_method: [
        {required: true, message: '处理方法不能为空', trigger: 'change'},
      ],
      remarks: [
        {required: true, message: '审批意见不能为空', trigger: 'blur'},
      ],
      cluster_name: [
        {required: true, message: '请选择资源池', trigger: 'change'},
      ],
      actual_disk_size: [
        {required: true, message: '数据盘大小不能为空', trigger: 'change'},
      ]
    },
    doSubmit: doVmSubmit,
    doSelectFlavor: doAllocationSelectFlavor,
    doSelectCluster: doSelectCluster,
    options: {
      process_method: [
        {value: 1, label: '同意'},
        {value: 2, label: '驳回'}
      ]
    },
    table_data: [],
    visible: false,
    title: '计算（存储）资源分配',
    is_edit: true
  },
  netConfirmDialog: {
    editId: -1,
    editIndex: -1,
    editNetId: -1,
    editNetIndex: -1,
    form: {
      table_data: [],
      process_method: 1,
      remarks: '请按照相关要求使用网络资源',
    },
    rules: {
      process_method: [
        {required: true, message: '处理方法不能为空', trigger: 'change'},
      ],
      remarks: [
        {required: true, message: '审批意见不能为空', trigger: 'blur'},
      ],
      ipaddress: [
        {required: true, message: 'IP地址不能为空', trigger: 'blur'},
        {validator: validateIP, trigger: 'blur'}
      ],
      netmask: [
        {required: true, message: '掩码不能为空', trigger: 'blur'},
        {validator: subnetMaskValidator, trigger: 'blur'}
      ],
      gateway: [
        {required: true, message: '网关不能为空', trigger: 'blur'},
        {validator: validateIP, trigger: 'blur'},
      ],
      vlan_id: [
        {required: true, message: 'VlanID不能为空', trigger: 'blur'},
      ]
    },
    doSubmit: doNetSubmit,
    options: {
      process_method: [
        {value: 1, label: '同意'},
        {value: 2, label: '驳回'}
      ],
      net_location: [
        {label: '内部服务网', value: 1},
        {label: '外部服务网', value: 2}
      ],
      security_domain: [
        {label: '基础设施区', value: 1},
        {label: '数据服务区', value: 2},
        {label: '应用服务区', value: 3},
        {label: '托管服务区', value: 4},
      ]
    },
    table_data: [],
    visible: false,
    title: '网络资源分配',
    is_edit: true,
  },
  order_detail: {
    order_id: '',
    apply_depart: "",
    apply_person: "",
    contact_person: "",
    contact_phone: "",
    app_name: "",
    remarks: "",
    order_file: []
  },
  orderViewDrawer: {
    visible: false,
    vm_table:[],
    net_table:[],
    order_history:[]
  }

})

const shortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      end.setTime(end.getTime() + 3600 * 1000 * 24)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]


function clearForm() {
  state.applyForm.form = {
    contact_person: "",
    contact_phone: "",
    app_name: "",
    remarks: "",
    apply_datetime: new Date()
  }
  state.fileForm.fileList = []
  state.netForm.form = {
    net_location: '',
    net_location_text: '',
    security_domain: '',
    security_domain_text: '',
    resource_name: ''
  }
  state.netTableData = []
  state.vmForm.form = {
    vm_name: '',
    cpu_arch: 1,
    cpu_arch_text: '',
    flavor: '',
    flavor_text: '',
    vcpu: '',
    memory: '',
    net_location: "",
    security_domain: "",
    disk_size: 100,
    os: "",
    os_text: '',
  }
  state.vmTableData = []
  if (applyFormRef.value) {
    applyFormRef.value.resetFields()
  }
  if (vmFormRef.value) {
    vmFormRef.value.resetFields()
  }
  if (netFormRef.value) {
    netFormRef.value.resetFields()
  }
}

function uploadSuccess(res, file, fileList) {
  if (res.code === 0) {
    let file_dic = {
      uid: file.uid,
      name: file.name,
      url: res.data.data.url,
      save_url: res.data.data.save_url,
      abs_url: res.data.data.abs_url
    }
    state.fileForm.fileList.push(file_dic)
  } else {
    ElMessage.error(res.detail)
    state.fileForm.fileList = fileList.filter(item => item.uid !== file.uid)
  }
}

function beforeUpload(file) {
  const allowedTypes = [
    'image/jpeg',
    'image/png',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ]
  const isValidType = allowedTypes.includes(file.type)

  // 文件大小限制 (2MB)
  const upload_max_size = 50
  const isLt50 = file.size / 1024 / 1024 < upload_max_size

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF/DOC/DOCX/XLS/XLSX 格式的文件!')
    return false
  }
  if (!isLt50) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  return true
}

function handleRemove(file, fileList) {
  let delete_file = state.fileForm.fileList.filter(item => item.uid === file.uid)[0]
  state.fileForm.fileList = state.fileForm.fileList.filter(item => item.uid !== file.uid)
  if (file.status === "success") {
    _axios.post('/api/web/order/delete/', {
      url: delete_file.save_url,
      file_name: file.name,
      edit_id: state.editId
    }).then((res) => {
      if (res.data.code === 0) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error("删除失败")
      }
    })
  }
}

function handlePreview(file) {
  let file_view = state.fileForm.fileList.filter(item => item.uid === file.uid)[0]
  const link = document.createElement('a')
  link.href = file_view.abs_url
  link.download = file.name
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

function handleExceed(file, fileList) {
  ElMessage.warning(`最多上传 6 个文件，您已选择了 ${file.length + fileList.length} 个文件`)
}

const cpu_arch_label = computed(() => {
  const option = state.vmForm.options.cpu_arch.find(item => item.value === state.vmForm.form.cpu_arch);
  return option ? option.label : '';
});
const vm_net_location_label = computed(() => {
  const option = state.vmForm.options.net_location.find(item => item.value === state.vmForm.form.net_location);
  return option ? option.label : '';
});
const vm_security_domain_label = computed(() => {
  const option = state.vmForm.options.security_domain.find(item => item.value === state.vmForm.form.security_domain);
  return option ? option.label : '';
});
const net_net_location_label = computed(() => {
  const option = state.vmForm.options.net_location.find(item => item.value === state.netForm.form.net_location);
  return option ? option.label : '';
});
const net_security_domain_label = computed(() => {
  const option = state.vmForm.options.security_domain.find(item => item.value === state.netForm.form.security_domain);
  return option ? option.label : '';
});

function doNetEdit(row, index) {
  if (row.order_status === 1) {
    ElMessage.warning('工单处于申请状态，不能分配资源')
    return
  }
  if (row.order_status === 3) {
    ElMessage.warning('工单已经完成分配！')
    return
  }
  if (allocationNetRuleForm.value.ruleForm) {
    allocationNetRuleForm.value.ruleForm.resetFields()
  }
  let last_index = row.order_confirm.findLastIndex(item => item.workflow === 1)
  if (last_index > -1) {
    let event_list = row.order_confirm.slice(last_index)
    let net_confirm_index = event_list.findLastIndex(item => item.workflow === 3)
    if (net_confirm_index > -1) {
      state.netConfirmDialog.is_edit = false
      state.netConfirmDialog.form.remarks = event_list[net_confirm_index].remarks
    }else{
      state.netConfirmDialog.is_edit = true
    }
  }
  state.netConfirmDialog.editId = row.id
  state.netConfirmDialog.editIndex = index
  state.netConfirmDialog.visible = true
  state.netConfirmDialog.order_id = row.id
  state.netConfirmDialog.form.table_data = row.apply_net
  state.order_detail.order_id = row.order_id
  state.order_detail.apply_depart = row.apply_depart
  state.order_detail.apply_person = row.apply_person
  state.order_detail.contact_person = row.contact_person
  state.order_detail.contact_phone = row.contact_phone
  state.order_detail.app_name = row.app_name
  state.order_detail.remarks = row.remarks
  state.order_detail.order_file = row.order_file
}

function doNetSubmit(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (state.netConfirmDialog.editId > 0) {
        _axios.post(`/api/web/order/${state.netConfirmDialog.editId}/confirm/net/`, state.netConfirmDialog.form).then((res) => {
          if (res.data.code === 0) {
            state.netConfirmDialog.editId = -1
            state.netConfirmDialog.editIndex = -1
            state.netConfirmDialog.visible = false
            initTableData()
          } else {
            ElMessage.error("编辑失败")
          }
        })
      }
    } else {
      console.log("校验失败")
    }
  })
}

function doVmEdit(row, index) {
  if (row.order_status === 1) {
    ElMessage.warning('工单处于申请状态，不能分配资源')
    return
  }
  if (row.order_status === 3) {
    ElMessage.warning('工单已经完成分配！')
    return
  }
  if (row.apply_vm.length < 1) {
    ElMessage.warning('该工单没有申请计算资源!')
    return
  }
  if (allocationVmRuleForm.value.ruleForm) {
    allocationVmRuleForm.value.ruleForm.resetFields()
  }
  let last_index = row.order_confirm.findLastIndex(item => item.workflow === 1)
  if (last_index > -1) {
    let event_list = row.order_confirm.slice(last_index)
    let vm_confirm_index = event_list.findLastIndex(item => item.workflow === 2)
    if (vm_confirm_index > -1) {
      state.vmConfirmDialog.is_edit = false
      state.vmConfirmDialog.form.remarks = event_list[vm_confirm_index].remarks
    }else{
      state.vmConfirmDialog.is_edit = true
    }
  }
  state.vmConfirmDialog.editId = row.id
  state.vmConfirmDialog.editIndex = index
  state.vmConfirmDialog.visible = true
  state.vmConfirmDialog.order_id = row.id
  state.vmConfirmDialog.form.table_data = row.apply_vm
  state.order_detail.order_id = row.order_id
  state.order_detail.apply_depart = row.apply_depart
  state.order_detail.apply_person = row.apply_person
  state.order_detail.contact_person = row.contact_person
  state.order_detail.contact_phone = row.contact_phone
  state.order_detail.app_name = row.app_name
  state.order_detail.remarks = row.remarks
  state.order_detail.order_file = row.order_file
}

function doVmSubmit(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (state.vmConfirmDialog.editId > 0) {
        _axios.post(`/api/web/order/${state.vmConfirmDialog.editId}/confirm/vm/`, state.vmConfirmDialog.form).then((res) => {
          if (res.data.code === 0) {
            state.vmConfirmDialog.editId = -1
            state.vmConfirmDialog.editIndex = -1
            state.vmConfirmDialog.visible = false
            initTableData()
          } else {
            ElMessage.error("编辑失败")
          }
        })
      }
    }
  })
}

onMounted(() => {
  initTableData()
})

function initOsTable() {
  if (hasPermission2("order-os", "get")) {
    _axios.get("/api/web/order/os/").then((res) => {
      if (res.data.code === 0) {
        state.osDrawer.tableData = res.data.data;
      }
    })
  }
}

function initFlavorTable(drawer) {
  if (hasPermission2("order-flavor", "get")) {
    _axios.get("/api/web/order/flavor/").then((res) => {
      if (res.data.code === 0) {
        if (drawer === "apply") {
          state.flavorDrawer.tableData = res.data.data;
        } else {
          state.allocationflavorDrawer.tableData = res.data.data;
        }

      }
    })
  }
  ;
}

function doSelectOs() {
  initOsTable()
  state.osDrawer.id = ""
  state.osDrawer.visible = true
}

function doSelectFlavor() {
  initFlavorTable("apply")
  state.flavorDrawer.id = ""
  state.flavorDrawer.visible = true
}

function doAllocationSelectFlavor(row, index) {
  state.vmConfirmDialog.editVmId = row.id
  state.vmConfirmDialog.editVmIndex = index
  state.allocationflavorDrawer.id = row.actual_flavor
  initFlavorTable("allocation")
  state.allocationflavorDrawer.visible = true
}


function doSelectCluster(row, index) {
  state.vmConfirmDialog.editVmId = row.id
  state.vmConfirmDialog.editVmIndex = index
  state.clusterDrawer.id = row.cluster || null
  state.clusterDrawer.visible = true
}

function doAddVm(formEl) {
  formEl.validate((valid, fields) => {
    if (!valid) return
    let vm_dict = {
      vm_name: state.vmForm.form.vm_name,
      cpu_arch: state.vmForm.form.cpu_arch,
      cpu_arch_text: cpu_arch_label.value,
      flavor: state.vmForm.form.flavor,
      flavor_text: `${state.vmForm.form.vcpu}核|${state.vmForm.form.memory}GB`,
      net_location: state.vmForm.form.net_location,
      net_location_text: vm_net_location_label.value,
      security_domain: state.vmForm.form.security_domain,
      security_domain_text: vm_security_domain_label.value,
      disk_size: state.vmForm.form.disk_size,
      os: state.vmForm.form.os,
      os_text: state.vmForm.form.os_text,
    }
    let net_dict = {
      flag: true,
      resource_name: state.vmForm.form.vm_name,
      net_location: state.vmForm.form.net_location,
      net_location_text: vm_net_location_label.value,
      security_domain: state.vmForm.form.security_domain,
      security_domain_text: vm_security_domain_label.value,
    }
    state.netTableData.push(net_dict)
    state.vmTableData.push(vm_dict)
  })
}

function doAddNet(formEl) {
  formEl.validate((valid, fields) => {
    if (!valid) return
    let vm_dict = {
      flag: false,
      resource_name: state.netForm.form.resource_name,
      net_location: state.netForm.form.net_location,
      net_location_text: net_net_location_label.value,
      security_domain: state.netForm.form.security_domain,
      security_domain_text: net_security_domain_label.value,
    }
    state.netTableData.push(vm_dict)
  })
}

function confirmDelete(row, index) {
  let order_status = row.order_status
  if (order_status === 2) {
    ElMessage.warning("工单为待分配状态，禁止删除！")
    return
  }
  if (order_status === 3) {
    ElMessage.warning("工单为已分配状态，禁止删除！")
    return
  }
  _axios.delete(`/api/web/order/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function resetVmForm() {
  vmFormRef.value.resetFields()
}

function resetNetForm() {
  netFormRef.value.resetFields()
}

function doClusterClickRow(val) {
  state.clusterDrawer.id = val.id
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].cluster_name = val.cluster_name
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].cluster = val.id
  state.clusterDrawer.visible = false
}

function doAllocationFlavorClickRow(val) {
  state.allocationflavorDrawer.id = val.id
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].actual_flavor = val.id
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].actual_flavor_text = `${val.vcpu}核|${val.memory}GB`
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].vcpu = val.vcpu
  state.vmConfirmDialog.form.table_data[state.vmConfirmDialog.editVmIndex].memory = val.memory
  state.allocationflavorDrawer.visible = false
}

function doFlavorClickRow(val) {
  state.flavorDrawer.id = val.id
  state.vmForm.form.flavor = val.id
  state.vmForm.form.flavor_text = val.title
  state.vmForm.form.vcpu = val.vcpu
  state.vmForm.form.memory = val.memory
  state.flavorDrawer.visible = false
}

function doOsClickRow(val) {
  state.osDrawer.id = val.id
  state.vmForm.form.os_text = `${val.os_name}-${val.version}`
  state.vmForm.form.os = val.id
  state.osDrawer.visible = false
}

function doResetSearchForm() {
  searchFormRef.value.resetFields()
}

function doSearch() {
  state.pager.currentPage = 1
  initTableData()
}


function initTableData() {
  if (!hasPermission2("order-list", "get")) {
    return
  }
  state.isLoading = true
  let search_params = {page: state.pager.currentPage, page_size: state.pager.perPageSize}
  for (let key in state.searchForm) {
    let value = state.searchForm[key]
    if (key === "options") {
      continue
    }
    if (!value) {
      continue
    }
    if (key === "date_range") {
      search_params["start_date"] = value[0]
      search_params["end_date"] = value[1]
    } else {
      search_params[key] = value
    }
  }
  _axios.get("/api/web/order/", {params: search_params}).then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data.data;
      state.pager.totalCount = res.data.data.totalCount;
      state.pager.perPageSize = res.data.data.perPageSize
      state.isLoading = false
    }
  })
}


function handleChangePage(page) {
  state.pager.currentPage = page
  initTableData()
}

function handleSizeChange(page_size) {
  localStorage.setItem("pageSize", page_size)
  state.pager.perPageSize = page_size
  state.pager.currentPage = 1
  initTableData()
}

function doAdd() {

  state.dialog.visible = true
  state.dialog.title = "资源申请"
  state.editId = -1
  state.editIndex = -1
  clearForm()
}

function doEdit(row, index) {
  let order_status = row.order_status
  if (order_status === 2) {
    ElMessage.warning("工单为待分配状态，禁止编辑！")
    return
  }
  if (order_status === 3) {
    ElMessage.warning("工单已完成分配，禁止编辑！")
    return
  }
  state.dialog.visible = true
  state.dialog.title = '修改申请'
  state.editId = row.id
  state.editIndex = index

  if (applyFormRef.value) {
    applyFormRef.value.resetFields()
  }
  if (vmFormRef.value) {
    vmFormRef.value.resetFields()
  }
  if (netFormRef.value) {
    netFormRef.value.resetFields()
  }

  state.applyForm.form = {
    contact_person: row.contact_person,
    contact_phone: row.contact_phone,
    app_name: row.app_name,
    remarks: row.remarks,
    apply_datetime: new Date()
  }
  state.fileForm.fileList = row.order_file
  state.vmTableData = row.apply_vm
  state.netTableData = row.apply_net
}


function vmConfirmDelete(index, row) {
  let delete_idx = state.netTableData.findIndex(item => item.flag === 1 && item.resource_name === row.vm_name)
  state.vmTableData.splice(index, 1)
  state.netTableData.splice(delete_idx, 1)
}

function netConfirmDelete(index, row) {
  state.netTableData.splice(index, 1)
}

function doReset() {
  applyFormRef.value.resetFields()
}

function doSave() {
  applyFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (state.editId > 0) {
        _axios.put(`/api/web/order/${state.editId}/`, {
          order: state.applyForm.form,
          apply_vm: state.vmTableData,
          apply_net: state.netTableData,
          file_list: state.fileForm.fileList,
          change_order_status: false
        }).then((res) => {
          if (res.data.code === 0) {
            state.tableData[state.editIndex] = res.data.data
            state.editId = -1
            state.editIndex = -1
            state.dialog.visible = false
          } else {
            ElMessage.error("编辑失败")
          }
        })
      } else {
        state.dialog.errors = {}
        _axios.post('/api/web/order/', {
          order: state.applyForm.form,
          apply_vm: state.vmTableData,
          apply_net: state.netTableData,
          file_list: state.fileForm.fileList,
          change_order_status: false
        }).then((res) => {
          if (res.data.code === 0) {
            //state.tableData.unshift(res.data.data)
            state.dialog.visible = false
            initTableData()
          } else {
            ElMessage.error("添加失败")
          }
        })
      }
    }
  })
}

function doSubmit() {
  if (state.fileForm.fileList.length < 1) {
    ElMessage.warning("附件不能为空")
    return
  }
  console.log(state.vmTableData.length, state.netTableData.length)
  if (state.vmTableData.length < 1 && state.netTableData.length < 1) {
    ElMessage.warning("申请资源不能为空")
    return
  }
  applyFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (state.editId > 0) {
        _axios.put(`/api/web/order/${state.editId}/`, {
          order: state.applyForm.form,
          apply_vm: state.vmTableData,
          apply_net: state.netTableData,
          file_list: state.fileForm.fileList,
          change_order_status: true
        }).then((res) => {
          if (res.data.code === 0) {
            state.tableData[state.editIndex] = res.data.data
            state.editId = -1
            state.editIndex = -1
            state.dialog.visible = false
          } else {
            ElMessage.error("编辑失败")
          }
        })
      } else {
        state.dialog.errors = {}
        _axios.post('/api/web/order/', {
          order: state.applyForm.form,
          apply_vm: state.vmTableData,
          apply_net: state.netTableData,
          file_list: state.fileForm.fileList,
          change_order_status: true
        }).then((res) => {
          if (res.data.code === 0) {
            //state.tableData.unshift(res.data.data)
            state.dialog.visible = false
            initTableData()
          } else {
            ElMessage.error("添加失败")
          }
        })
      }
    }
  })
}

function doView(row, index) {
  state.orderViewDrawer.order_history = row.order_history
  state.orderViewDrawer.visible = true
  state.orderViewDrawer.vm_table = row.apply_vm
  state.orderViewDrawer.net_table = row.apply_net
  state.order_detail.order_id = row.order_id
  state.order_detail.apply_depart = row.apply_depart
  state.order_detail.apply_person = row.apply_person
  state.order_detail.contact_person = row.contact_person
  state.order_detail.contact_phone = row.contact_phone
  state.order_detail.app_name = row.app_name
  state.order_detail.remarks = row.remarks
  state.order_detail.order_file = row.order_file
}
</script>

<style scoped>
.header {
  color: #FFFFFF;
  height: 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: rgb(51.2, 126.4, 204);

}

.card {
  margin-left: 30px;
  margin-right: 40px;
  margin-top: 5px;
}


.resource-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.resource-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}

.resource-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}


.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>